// Spawn 会衍生子进程，且不会阻塞 Node.js 事件循环
import { execSync, spawn } from 'node:child_process'

import { readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'

// 升级 package.json
const packageJson = JSON.parse(readFileSync(resolve('./package.json'), 'utf-8'))
const { version } = packageJson
console.log(version)

const newVersion = version
  .split('.')
  .map((v, i) => (i === 2 ? Number.parseInt(v) + 1 : v))
  .join('.')
packageJson.version = newVersion
writeFileSync('package.json', JSON.stringify(packageJson, null, 2))

// git commit
execSync('git add .', { stdio: 'inherit' })
execSync(`git commit -m "chore: upgrade version to ${newVersion}"`, { stdio: 'inherit' })

// npm 发布
// execSync(`npm publish --registry https://registry.npmjs.org --no-git-checks --access public`, {
//   stdio: 'inherit',
// });

// 上传 git
execSync('git push', { stdio: 'inherit' })

execCommand('git', ['tag', '-a', `v${packageJson.version}`, '-m', `Version${packageJson.version}`])
execCommand('git', ['push', 'origin', '--tags'])

function execCommand(...args) {
  return new Promise((resolve, reject) => {
    // `sqawn()函数` 本质上会开启一个进程，并返回一个 子进程（childProcess）
    const childProcess = spawn(...args)

    // 执行过程中能显示很多打印信息
    childProcess.stdout.pipe(process.stdout)
    childProcess.stderr.pipe(process.stderr)

    childProcess.on('close', () => {
      resolve('npm install execution')
    })
  })
}
